package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.SAXParser;
import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration= configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
//        解析输入流，获得配置文件信息
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
//        List<Element> selectNodes = rootElement.selectNodes("//select");
        List<Element> allElements = rootElement.elements();

        String namespace = rootElement.attributeValue("namespace");
        for (Element element : allElements) {
            String qualifiedName = element.getQualifiedName();
//            解析配置文件
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            mappedStatement.setQualifiedName(qualifiedName);
            configuration.getMappedStatementMap().put(namespace+"."+id,mappedStatement);
        }
    }
}
